package com.cmccgz.udacs_landlord_webapp.main.user.userinfo;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.BaseFragment;
import com.cmccgz.baselibrary.image.GlideUtils;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.photoview.ImageShowActivity;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.UserInfo;
import com.cmccgz.udacs_landlord_webapp.main.host.HostActivity;
import com.cmccgz.udacs_landlord_webapp.main.user.login.LoginActivity;
import com.cmccgz.udacs_landlord_webapp.update.PackageUtils;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;
import com.orhanobut.logger.Logger;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.cmccgz.baselibrary.view.photoview.ImageShowActivity.KEY_IMGE_URLS;

/**
 * @author INX
 * 用户信息fragment
 */
public class UserInfoFragment extends BaseFragment implements View.OnClickListener,UserInfoContract.UserInfoView{
    private UserInfoActivity parentActivity;
    private LinearLayout ll_change_pwd, ll_check_update, ll_logout;
    private TextView tv_editUserInfo,tv_userName;
    private ImageView iv_editUserInfo;
    private ImageView ci_header,iv_bg;
    private TextView tv_version;
    private UserInfoContract.UserInfoPresenter presenter;
    private UserInfo userInfo;
    private LinearLayout ll_share;

    public static UserInfoFragment instance(){
        return new UserInfoFragment();
    }
    @Override
    protected int setLayoutId() {
        return R.layout.fragment_userinfo;
    }

    @Override
    protected void initView() {
        parentActivity = ((UserInfoActivity) mContext);
        ViewHelper viewHelper = ViewHelper.instance(this);
        if (viewHelper!=null) {
            viewHelper.setBackTextVisable(true);
            viewHelper.setTitle(R.string.title_userinfo);
        }
        ll_change_pwd = ((LinearLayout) findViewById(R.id.ll_change_pwd));
        ll_check_update = ((LinearLayout) findViewById(R.id.ll_check_update));
        ll_share = ((LinearLayout) findViewById(R.id.ll_share));
        ll_logout = ((LinearLayout) findViewById(R.id.ll_logout));
        tv_editUserInfo = ((TextView) findViewById(R.id.tv_editUserInfo));
        tv_userName = ((TextView) findViewById(R.id.tv_userName));
        tv_version = (TextView) findViewById(R.id.tv_version);
        iv_editUserInfo = ((ImageView) findViewById(R.id.iv_editUserInfo));
        ci_header = ((ImageView) findViewById(R.id.ci_header));
        iv_bg = ((ImageView) findViewById(R.id.iv_bg));
        ll_change_pwd.setOnClickListener(this);
        ll_check_update.setOnClickListener(this);
        ll_share.setOnClickListener(this);
        ll_logout.setOnClickListener(this);
        tv_editUserInfo.setOnClickListener(this);
        iv_editUserInfo.setOnClickListener(this);
        ci_header.setOnClickListener(this);
        presenter= new UserInfoPresenter(this);
        if (isSaveInstance&&getSavedInstanceState()!=null) {
           userInfo= (UserInfo) getSavedInstanceState().getSerializable("userInfo");
        }
        presenter.getUserInfo();
        tv_version.setText("当前版本：V"+PackageUtils.getAppVersionName(mContext));

        ll_share.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("appUrl", AppConfig.getAppUrl());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtils.toastShort(mContext,"已复制下载链接！");
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        setClickSpan(v,1000);
        switch (v.getId()) {
            case R.id.tv_back:
                parentActivity.onBackPressed();
                break;
            case R.id.ll_change_pwd:
                parentActivity.changePwd(null);
                break;
            case R.id.ll_check_update:
                parentActivity.checkUpdate();
                break;
            case R.id.ll_logout:
//                JPushInterface.deleteAlias(mContext, 0);
                AppConfig.setMobile(mContext,"");
                mContext.sendBroadcast(new Intent(HostActivity.CLOSE_HOST));
                startActivity(new Intent(mContext, LoginActivity.class));
                ((BaseActivity) mContext).finish(false);
                break;
            case R.id.tv_editUserInfo:
            case R.id.iv_editUserInfo:
                if (userInfo==null) {
                    showToast(R.string.tips_userinfo_no_get);
                    presenter.getUserInfo();
                    break;
                }
                parentActivity.setUserInfo(userInfo);
                parentActivity.changeUserInfo();
                break;
            case R.id.ci_header:
                String headerUrls = userInfo.getImagePath();
                if (StringUtils.isEmpty(headerUrls)) {
                    showToast(getString(R.string.tips_header_no_set));
                    break;
                }
                Intent intent = new Intent(mContext, ImageShowActivity.class);
                List<String>urls=new ArrayList<>();
                urls.add(headerUrls);
                intent.putExtra(KEY_IMGE_URLS, ((Serializable) urls));
                startActivity(intent);
                break;
            case R.id.ll_share:
                shareApp();
                break;
        }
    }

    public void shareApp() {
        //                http://baseUrl/appDownload?app_id=CMCCGZ_UDACS
        Intent subIntent = new Intent(Intent.ACTION_SEND);
        subIntent.setType("text/plain");
        String appUrl =AppConfig.getAppUrl();
        subIntent.putExtra(Intent.EXTRA_TEXT,"正在分享'"+mContext.getString(R.string.app_name)+"'下载链接："+ appUrl);
        startActivity(Intent.createChooser(subIntent,"分享'" + mContext.getString(R.string.app_name)+"'"),false);
    }

    /**
     * 更新用户信息界面
     * @param userInfo
     */
    private void updateUserInfoView(final UserInfo userInfo){
        if (userInfo==null) {
            return;
        }
        parentActivity.setUserInfo(userInfo);
        final String imagePath = userInfo.getImagePath();
        if (StringUtils.isEmpty(imagePath)) {
            switch (userInfo.getSex()) {
                case "男":
                    iv_bg.setImageResource(R.mipmap.img_touxiang);
                    ci_header.setImageResource(R.mipmap.img_touxiang);
                    break;
                case "女":
                    iv_bg.setImageResource(R.mipmap.img_tx_nv);
                    ci_header.setImageResource(R.mipmap.img_tx_nv);
                    break;
            }
        }else{
            loadHeader(imagePath);
        }

        String nick_name = userInfo.getNick_name();
        if (!StringUtils.isEmpty(nick_name)) {
            tv_userName.setText(nick_name);
        }
        this.userInfo = userInfo;
    }

    /**
     * 加载头像
     * @param imagePath
     */
    private void loadHeader(final String imagePath) {
        Logger.v("用户头像："+imagePath);
        GlideUtils.loadImage(mContext, imagePath, iv_bg);
        GlideUtils.loadImage(mContext, imagePath, ci_header);
//        GlideUtils.loadHeadImage(mContext,imagePath,ci_header, com.cmccgz.baselibrary.R.drawable.n_photo_default,null);
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo(){
        presenter.getUserInfo();
    }

    /**
     * 获取用户信息缓存
     * @param userInfo
     */
    @Override
    public void getUserInfoCache(UserInfo userInfo) {
        updateUserInfoView(userInfo);
    }

    /**
     * 获取用户信息成功
     * @param userInfo
     */
    @Override
    public void getUserInfoSuccess(UserInfo userInfo) {
         updateUserInfoView(userInfo);
    }

    /**
     * 获取用户信息失败
     * @param msg
     */
    @Override
    public void getUserInfoFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("userInfo",userInfo);
        parentActivity.setUserInfo(userInfo);
        super.onSaveInstanceState(outState);
    }
}
